<?php
/*
* 用户账户模块
**/
class Account extends CI_Controller{

	function __construct(){
		parent::__construct();
		$this->load->helper(array('url','form'));
		include APPPATH."config/ucenter.php";
		include APPPATH."../uc_client/client.php";
		
	}
	
	function index(){
	
		$this->load->model('user_model');
		if(!$this->user_model->islogin()){
			set_session('backurl','account');
			$this->login();
		
		}else{
			$data = array(
				'userinfo' => $this->user_model->userProfile(guser('id'))
			);
			$this->load->view('templates/header');
			$this->load->view('account/home',$data);
			$this->load->view('templates/footer');
		}
	
	}
		//编辑用户资料
	function profile(){
	
		$this->load->model('user_model');
		if(!$this->user_model->islogin()){
			set_session('backurl','account/profile');
			$this->login();
		
		}else{
			$action = $this->input->post('action');
			if(!empty($action) && $action == 'update'){
				$password = trim($this->input->post('password'));
				$repassword = trim($this->input->post('repassword'));
				$this->load->library("form_validation");
		
				$rules = array(				
					array(
						'field' => 'password',
						'label' => '密码',
						'rules' => 'trim'
					),				
					array(
						'field' => 'repassword',
						'label' => '重复密码',
						'rules' => 'trim|matches[password]|md5'
					),				
					array(
						'field' => 'email',
						'label' => '邮箱',
						'rules' => 'trim|required|valid_email|callback_email_check'
					)
				
				);
				$this->form_validation->set_rules($rules);
				
				if($this->form_validation->run() === true){
					
					$data = array(
						'email' => $this->input->post('email')					
					);
					
					
					
					$attrdata = array(
						'sex' => (int)$this->input->post('sex'),
						'birthday' => $this->input->post('birthday'),
						'address' => $this->input->post('address'),
						'constellation' => (int)$this->input->post('constellation')
					);
					
					//更新密码
					if( $password !="" && $password == $repassword ){
						//uc同步更新用户资料,包括密码(不验证旧密码)
						$uc_edit = uc_user_edit(guser('username'), '', $password, $data['email'], 1);
						$data['password'] = encryptUserPassword($pessaword);
					}else{
						//uc同步更新用户资料(不验证旧密码)
						$uc_edit = uc_user_edit(guser('username'), '', '', $data['email'], 1);
					}
				
					
					
					
					//成功更新
					if($uc_edit >= 0){
						$upuser = $this->user_model->editUser($data,array('id'=>guser('id')));
						$upprofile = $this->user_model->editProfile($attrdata,guser('id'));
				
						if( $upuser && $upprofile ){
							if($password !="" && $password == $repassword){
								
								set_session('location','account/logout');
								showMessage('资料成功更新，请退出重新登陆！',0,'success');
							}else{
								
								set_session('location','account');
								showMessage('资料成功更新！',0,'success');
							}
							
						}
					}else{
						set_session('location','account/profile');
						showMessage('资料更新失败!',0,'error');
					}
				
				
				}else{
					
					
					$data = array(
						'userinfo' => $this->user_model->userProfile(guser('id'))
					);
					$this->load->view('templates/header');
					$this->load->view('account/profile',$data);
					$this->load->view('templates/footer');
				}
				
				
			}else{
				$data = array(
					'userinfo' => $this->user_model->userProfile(guser('id')),
					'avatar' => uc_avatar(guser('id'),'virtual',1)
				);
				$this->load->view('templates/header');
				$this->load->view('account/profile',$data);
				$this->load->view('templates/footer');
			}

		}
	}
	
	//编辑头像
	function avatar(){
		$data = array('avatar' => uc_avatar(guser('id'),'virtual',1));
		$this->load->view('templates/header');
		$this->load->view('account/avatar',$data);
		$this->load->view('templates/footer');
	}
	
	//找回密码
	function get_password(){
		if($this->user_model->islogin()){
			showMessage('当前处在登录状态，如果忘记密码请修改密码',array('修改密码'=>"account/profile",'个人中心'=>"account"));
		}
		
		$action = $this->input->post('action');
		if($action == 'send_password'){
			$this->load->library("form_validation");
		
				$rules = array(				
		
					array(
						'field' => 'username',
						'label' => '用户名',
						'rules' => 'trim|required'
					),				
					array(
						'field' => 'email',
						'label' => '邮箱',
						'rules' => 'trim|required|valid_email'
					)
				
				);
				$this->form_validation->set_rules($rules);
				
				if($this->form_validation->run() === true){
					$username = $this->input->post('username');
					$email = $this->input->post('email');
					
					//在ucenter中验证用户
					list($uc_uid, $uc_username, $uc_email) = $uc_userinfo = uc_get_user($username);
				
					if($uc_userinfo){
						//用户和邮箱对应
						if($email == $uc_email){
							
							//发送更改密码的邮件
							$salt = md5(md5(time()).$uc_email);
							$send = sendEmail('yongtao.li@zopomobile.com',$uc_email,"请点击<a href=$url>更新密码</a>链接更改密码",'更新密码通知','smtp');
							if($send){
								$this->user_model->addEmailLog($uc_uid,$uc_email);
								showMessage('已发送邮件到邮箱:'.$uc_email."请查收!");
							}else{
								set_session('location','account/get_password');
								showMessage('发送邮件失败!'.$send,0,'error');
							}
						}else{
							$this->load->view('templates/header');
							$this->load->view('account/get_password',array('error'=>'用户名和邮箱不对应'));
							$this->load->view('templates/footer');
						}
					
					//用户不存在
					}else{
						$this->load->view('templates/header');
						$this->load->view('account/get_password',array('error'=>'用户不存在'));
						$this->load->view('templates/footer');
					}
				}else{
					$this->load->view('templates/header');
					$this->load->view('account/get_password');
					$this->load->view('templates/footer');
				}
		}else{
			$this->load->view('templates/header');
			$this->load->view('account/get_password');
			$this->load->view('templates/footer');
		}
		
		
		
		
	}

	//登陆视图
	function login(){
		$this->load->model('user_model');
		
		//记住密码后直接登录成功
		$remember_user = $this->session->userdata('remember_user');
		if(!empty($remember_user)){
			$this->loginaction();
		}
		
		if(!$this->user_model->islogin()){
				$captchaconf = $this->config->item('captcha');
				$data = array(
					'captchaconf' => $captchaconf
				);
				if($captchaconf['login_need']){
				
					$cap = captcha('app_captcha');

					$data['captcha'] = $cap['image'];
				}
				
				$this->load->view('templates/header');
				$this->load->view('account/login',$data);
				$this->load->view('templates/footer');
		}else{
		set_session('crefresh','account');
		showMessage('账户已登录!',0,'success');
		}

	}
	
	//执行登陆	
	function loginaction(){
		$this->load->library('form_validation');
		
		//登录需要验证码
		$captchaconf = $this->config->item('captcha');
		if($captchaconf['login_need']){
	
			if($postcaptch = $this->input->post('captcha')){
				
				$admin_captcha = $this->session->userdata('app_captcha');
				
				if(strtolower($postcaptch) != strtolower($admin_captcha['word'])){
					set_session('location','account');
					showMessage('验证码错误!',0,'error');
				}
			}else{
				set_session('location','account');
				showMessage('验证码未填写!',0,'error');
			}
		}
			
			
		$this->load->model('user_model');
		$username = $this->input->post('username');
		//$email = $this->input->post('email');
		$password = $this->input->post('password');
		
		//ucenter 验证登陆
		$uclogin = uc_user_login($username,$password);
		
		//ucenter登陆成功
		if( $uclogin[0] > 0 ){
		
			$data = array();
			$data['password'] =  encryptUserPassword($password);
			$data['email'] = $uclogin[3];
			$data['username'] = $username;
			$data['openid']  = $data['id'] = $uclogin[0];
			$data['uc_connect'] = 1;

			/**
			*提示：ucenter中的密码更新不能同步到应用，因此在登录时同步uc中用户数据(密码)到本地应用
			*/
			$user_exist =  $this->user_model->userInfo(array('username'=>$username));
			
			//用户不存在,则注册用户
			if(!$user_exist){
				$this->user_model->addUser($data);
				
			//用户存在更新用户的信息
			}else{
				$this->user_model->editUser($data,array('openid'=> $data['openid']));
			}
			
			//自动登录 coding...
			if($this->input->post('remember')){
				set_session('remember_user',$this->session->userdata('user'));
			}

		
		
		//密码错误
		}else if($uclogin[0]  == -2){

			set_session('location','account/login');
			showMessage('密码错误,登录失败!',0,'error');
			return false;
			
		//ucenter中登录失败
		}else{

			set_session('location','account/login');
			showMessage('登录失败!',0,'error');
			return false;
		}
		

		if($backrefresh = $this->session->userdata('backurl')){
			set_session('location',$backrefresh);
			$this->session->unset_userdata('backurl');
		}else{
			set_session('location','home');
		}
		
		/**
		* uc同步登陆
		* uc同步数据需要输出js请求代码，防止在message模板前输出，存入缓冲区
		*/
		ob_start();
			print_r(uc_user_synlogin($uclogin[0]));
			$buffer = ob_get_contents();
		ob_end_clean();
		showMessage('登录成功!'.$buffer,0,'success');

	}
	
		
	//注册
	function register(){
		$this->load->model('user_model');
		if(!$this->user_model->islogin()){
			//注册需要验证码
			$captchaconf = $this->config->item('captcha');
			
			$this->load->library("form_validation");
		
			$rules = array(
				array(
					'field' => 'username',
					'label' => '用户名',
					'rules' => 'trim|required|callback_username_check'
				),				
				array(
					'field' => 'password',
					'label' => '密码',
					'rules' => 'trim|required'
				),				
				array(
					'field' => 'repassword',
					'label' => '重复密码',
					'rules' => 'trim|required|matches[password]|md5'
				),				
				array(
					'field' => 'email',
					'label' => '邮箱',
					'rules' => 'trim|required|valid_email|callback_email_check'
				)
			
			);
			$this->form_validation->set_rules($rules);
		
		
				if($this->form_validation->run() === true){
				
					
					if($captchaconf['register_need']){
				
						if($postcaptch = $this->input->post('captcha')){
							
							$app_captcha = $this->session->userdata('app_captcha');
							
							if(strtolower($postcaptch) != strtolower($app_captcha['word'])){
								set_session('location','account/register');
								showMessage('验证码错误!',0,'error');
							}
						}else{
							set_session('location','account/register');
							showMessage('验证码未填写!',0,'error');
						}
					}
			
			
					$this->load->library('encrypt');
					$data = array(
						'username' => $this->input->post('username'),
						'password' => encryptUserPassword($this->input->post('password')),
						'email' => $this->input->post('email'),
						'status' => 1
					);
					
					//ucenter中注册
					$uid = uc_user_register($data['username'], $this->input->post('password'), $data['email']);
					//uc中注册失败
					if($uid <= 0) {
							if($uid == -1) {
								$error =  '用户名不合法';
							} elseif($uid == -2) {
								$error =  '用户名包含不允许注册的词语';
							} elseif($uid == -3) {
								$error =   '用户名已经存在';
							} elseif($uid == -4) {
								$error =  'Email 格式有误';
							} elseif($uid == -5) {
								$error =  'Email 不允许注册';
							} elseif($uid == -6) {
								$error = '该 Email 已经被注册';
							} else {
								$error =  '发生错误请重试';
							}
						
							$captcha = captcha('app_captcha');
							$data = array(
								'register_need_captcha' => $captchaconf['register_need'],
								'captcha' => $captcha['image'],
								'error' => $error
							);
							
							$this->load->view('templates/header');
							$this->load->view('account/register',$data);
							$this->load->view('templates/footer');
					}else{
						
						$data['openid'] = $uid;
						$data['id'] = $uid;
					   
						//添加成功
						if($this->user_model->addUser($data)){
							
							showMessage('账户注册成功!',array('直接登录'=>'account/login'),'success');
						
						//添加失败
						}else{

							$this->load->view('templates/header');
							$this->load->view('account/register',$data);
							$this->load->view('templates/footer');
						}
						
				   }
					

				}else{
					$data = array(
						'register_need_captcha' => $captchaconf['register_need']
					);
					if($captchaconf['register_need']){
						$captcha = captcha('app_captcha');
						$data['captcha'] = $captcha['image'];
					}
					
					$this->load->view('templates/header');
					$this->load->view('account/register',$data);
					$this->load->view('templates/footer');
				}
	
			
		}else{
			$this->load->view('templates/header');
			$this->load->view('account/home');
			$this->load->view('templates/footer');
		}
	}
		
	//登出
	function logout(){
		$this->load->library('session');
		$this->session->unset_userdata('user');
		echo $ucloignout = uc_user_synlogout();
		set_session('location','account');
		showMessage('已退出系统',0,'info',0);
	}
	
	//验证用户存在
	public function username_check($username){
		if($this->user_model->userInfo(array('username'=>$username))){
			$this->form_validation->set_message('username_check', '%s 已经存在');
			return false;
		}else{
			return true;
		}
	}
	
	//验证邮箱存在
	public function email_check($email){
		$userinfo = $this->user_model->userInfo(array('email'=>$email));
		if($userinfo && $userinfo['id'] != (int)guser('id')){
			$this->form_validation->set_message('email_check', '%s 已经存在');
			return false;
		}else{
			return true;
		}
	}
	
	
	
	
}